package com.example.activity.implicitintent;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

public class SecondActivity extends AppCompatActivity {
    private TextView tvResult;
    private EditText etPhone;
    private User user;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);

        tvResult = findViewById(R.id.textView);
        etPhone = findViewById(R.id.et_phone);

        // 获取 MainActivity传递的数据，填充 SecondActivity相应的控件
        Intent intent = getIntent();
        Bundle extras = intent.getExtras();
        if (extras != null) {
            user = (User) extras.getSerializable("user");
            if (user != null) {
                tvResult.setText(user.getUsername());
                etPhone.setText(user.getPhone());
            }
        }
        // 设置按钮的事件监听器
        Button btnConfirm = findViewById(R.id.btn_confirm);
        btnConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 获取修改后的手机号，回传给 MainActivity
                String phone = etPhone.getText().toString();
                if(user != null) {
                    user.setPhone(phone);
                    Intent intent = new Intent();
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("user", user);
                    intent.putExtras(bundle);
                    setResult(RESULT_OK, intent);
                    SecondActivity.this.finish();
                }
            }
        });
    }
}